<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":true,"scrollpercent":true},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="Spring Data 概述">
<meta name="keywords" content="JPA,Spring Data">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Data JPA">
<meta property="og:url" content="http:&#x2F;&#x2F;beiran.top&#x2F;JPA&#x2F;Spring-Data-JPA&#x2F;index.html">
<meta property="og:site_name" content="北然">
<meta property="og:description" content="Spring Data 概述">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http:&#x2F;&#x2F;beiran.top&#x2F;JPA&#x2F;Spring-Data-JPA&#x2F;image-20200218181937666.png">
<meta property="og:image" content="http:&#x2F;&#x2F;beiran.top&#x2F;JPA&#x2F;Spring-Data-JPA&#x2F;JpaSpecificationExecutor_Function.png">
<meta property="og:updated_time" content="2020-02-18T11:48:10.696Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http:&#x2F;&#x2F;beiran.top&#x2F;JPA&#x2F;Spring-Data-JPA&#x2F;image-20200218181937666.png">

<link rel="canonical" href="http://beiran.top/JPA/Spring-Data-JPA/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>Spring Data JPA | 北然</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">北然</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">insomniac</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-schedule">

    <a href="/schedule/" rel="section"><i class="fa fa-fw fa-calendar"></i>日程表</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://beiran.top/JPA/Spring-Data-JPA/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/head.jpg">
      <meta itemprop="name" content="beiranc">
      <meta itemprop="description" content="你在想peach">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="北然">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring Data JPA
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-02-17 16:08:43" itemprop="dateCreated datePublished" datetime="2020-02-17T16:08:43+08:00">2020-02-17</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JPA/" itemprop="url" rel="index">
                    <span itemprop="name">JPA</span>
                  </a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h5 id="Spring-Data-概述"><a href="#Spring-Data-概述" class="headerlink" title="Spring Data 概述"></a>Spring Data 概述<a id="more"></a></h5><ol>
<li><a href="https://spring.io/projects/spring-data" target="_blank" rel="noopener">Spring Data</a> 是 Spring 的一个子项目，用于简化数据库访问，支持 NoSQL 与 关系型数据库。其主要目标是使数据库的访问变得方便快捷</li>
</ol>
<hr>
<h5 id="Spring-Data-JPA-概述"><a href="#Spring-Data-JPA-概述" class="headerlink" title="Spring Data JPA 概述"></a>Spring Data JPA 概述</h5><ol>
<li>Spring Data JPA：致力于减少 DAO 层的开发量，开发者只须声明持久层的接口即可</li>
<li>Spring Data JPA 做的便是规范方法的名字，根据符合规范的名字来确定方法需要实现什么样的逻辑</li>
</ol>
<hr>
<h5 id="Spring-Data-JPA-开发步骤"><a href="#Spring-Data-JPA-开发步骤" class="headerlink" title="Spring Data JPA 开发步骤"></a>Spring Data JPA 开发步骤</h5><ol>
<li><p>配置 Spring 整合 JPA（见 JPA ）</p>
</li>
<li><p>在 Spring 配置文件中配置 Spring Data，让 Spring 为声明的接口创建代理对象。配置了 &lt;jpa:repositories&gt; 后，Spring 初始化容器时将会扫描其 base-package 属性指定的包及其子包，为继承 Repository 接口或其子接口的接口创建代理对象，并将代理对象注入 Spring IOC 容器，业务层便可通过 Spring 自动封装的特性来直接使用该对象</p>
<ul>
<li><p>需导入 Spring Data Commons 和 Spring Data JPA 这两个主要模块</p>
</li>
<li><p>配置 Spring Data</p>
  <figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">jpa:repositories</span> <span class="attr">base-package</span>=<span class="string">"beiran.dao"</span> <span class="attr">entity-manager-factory-ref</span>=<span class="string">"entityManagerFactory"</span> <span class="attr">transaction-manager-ref</span>=<span class="string">"jpaTransactionManager"</span>&gt;</span><span class="tag">&lt;/<span class="name">jpa:repositories</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>声明持久层的接口，该接口继承 Repository 接口，Repository 是一个标记型接口，不包含任何方法，如需必要，Spring Data 可实现 Repository 的其他子接口，其中定义了一些常用的 CRUD 及分页相关的方法</p>
</li>
<li><p>在接口中声明需要的方法，Spring Data 将根据给定的策略来为其生成实现代码</p>
</li>
</ol>
<hr>
<h5 id="Repository-接口"><a href="#Repository-接口" class="headerlink" title="Repository 接口"></a>Repository 接口</h5><ol>
<li><p>Repository 接口是 Spring Data 的一个核心接口，它不提供任何方法，开发者需要在自己定义的接口声明需要的方法（声明的方法需要遵循规范）</p>
</li>
<li><p>可以在持久层接口上使用 @RepositoryDefinition 注解，并为其指定 domainClass（指定实体类） 和 idClass（指定该实体类的主键类型） 属性，这是与继承 Repository 接口等价的一种方式</p>
</li>
<li><p>基础的 Repository 接口提供了最基本的数据访问功能，它的几个子接口则扩展了一些功能</p>
<ul>
<li><p>Repository：仅仅是一个标记，表明任何继承它的接口均为持久层接口类</p>
</li>
<li><p>CrudRepository：继承 Repository，实现了一组 CRUD 相关的方法</p>
</li>
<li><p>PagingAndSortingRepository：继承 CrudRepository，实现了一组分页和排序相关的方法</p>
</li>
<li><p>JpaRepository：继承 PagingAndSortingRepository，实现一组 JPA 规范相关的方法</p>
</li>
<li><p>自定义的 XxxRepository 需要继承 JpaRepository，这样的 XxxRepository 接口就具备了通用的数据访问控制层的能力</p>
</li>
<li><p>JpaSpecificationExecutor：不属于 Repository 的子接口，实现一组 JPA Criteria 查询相关的方法</p>
<p><img src="image-20200218181937666.png" alt="image-20200218181937666"></p>
</li>
</ul>
</li>
</ol>
<hr>
<h5 id="Spring-Data-JPA-方法定义规范"><a href="#Spring-Data-JPA-方法定义规范" class="headerlink" title="Spring Data JPA 方法定义规范"></a>Spring Data JPA 方法定义规范</h5><ol>
<li><p>简单条件查询：查询某一个实体或者集合</p>
</li>
<li><p>按照 Spring Data JPA 的规范，查询方法以 find | read | get 开头，涉及条件查询时，条件的属性用条件关键字连接，要注意的是：条件属性以首字母大写，支持属性的级联查询，若当前类有符合条件的属性，则优先使用，而不使用级联属性，若需要使用级联属性，则属性之间使用 “_” 进行连接</p>
</li>
<li><p><a href="https://docs.spring.io/spring-data/jpa/docs/2.2.4.RELEASE/reference/html/#jpa.query-methods.query-creation" target="_blank" rel="noopener">支持的关键字</a></p>
<table>
<thead>
<tr>
<th>Keyword</th>
<th>Sample</th>
<th>JPQL snippet</th>
</tr>
</thead>
<tbody><tr>
<td>And</td>
<td>findByLastnameAndFirstname</td>
<td>… where x.lastname = ?1 and x.firstname = ?2</td>
</tr>
<tr>
<td>Or</td>
<td>findByLastnameOrFirstname</td>
<td>… where x.lastname = ?1 or x.firstname = ?2</td>
</tr>
<tr>
<td><code>Is</code>, <code>Equals</code></td>
<td><code>findByFirstname</code>, <code>findByFirstnameIs</code>, <code>findByFirstNameEquals</code></td>
<td>… where x.firstname = ?1</td>
</tr>
<tr>
<td>Between</td>
<td>findByStartDateBetween</td>
<td>… where x.startDate between ?1 and ?2</td>
</tr>
<tr>
<td>LessThan</td>
<td>findByAgeLessThan</td>
<td>… where x.age &lt; ?1</td>
</tr>
<tr>
<td>LessThanEqual</td>
<td>findByAgeLessThanEqual</td>
<td>… where x.age &lt;= ?1</td>
</tr>
<tr>
<td>GreaterThan</td>
<td>findByAgeGreaterThan</td>
<td>… where x.age &gt; ?1</td>
</tr>
<tr>
<td>GreaterThanEqual</td>
<td>findByAgeGreaterThanEqual</td>
<td>… where x.age &gt;= ?1</td>
</tr>
<tr>
<td>After</td>
<td>findByStartDateAfter</td>
<td>… where x.startDate &gt; ?1</td>
</tr>
<tr>
<td>Before</td>
<td>findByStartDateBefore</td>
<td>… where x.startDate &lt; ?1</td>
</tr>
<tr>
<td><code>IsNull</code>, <code>Null</code></td>
<td>findByAge(Is)Null</td>
<td>… where x.age is null</td>
</tr>
<tr>
<td><code>IsNotNull</code>, <code>NotNull</code></td>
<td>findByAge(Is)NotNull</td>
<td>… where x.age not null</td>
</tr>
<tr>
<td>Like</td>
<td>findByFirstnameLike</td>
<td>… where x.firstname like ?1</td>
</tr>
<tr>
<td>NotLike</td>
<td>findByFirstnameNotLike</td>
<td>… where x.firstname not like ?1</td>
</tr>
<tr>
<td>StartingWith</td>
<td>findByFirstnameStartingWith</td>
<td><code>… where x.firstname like ?1</code> (parameter bound with appended <code>%</code>)</td>
</tr>
<tr>
<td>EndingWith</td>
<td>findByFirstnameEndingWith</td>
<td><code>… where x.firstname like ?1</code> (parameter bound with prepended <code>%</code>)</td>
</tr>
<tr>
<td>Containing</td>
<td>findByFirstnameContaining</td>
<td><code>… where x.firstname like ?1</code> (parameter bound wrapped in <code>%</code>)</td>
</tr>
<tr>
<td>OrderBy</td>
<td>findByAgeOrderByLastnameDesc</td>
<td>… where x.age = ?1 order by x.lastname desc</td>
</tr>
<tr>
<td>Not</td>
<td>findByLastnameNot</td>
<td>… where x.lastname &lt;&gt; ?1</td>
</tr>
<tr>
<td>In</td>
<td>findByAgeIn(Collection ages)</td>
<td>… where x.age in ?1</td>
</tr>
<tr>
<td>NotIn</td>
<td>findByAgeNotIn(Collection&lt;Age&gt; ages)</td>
<td>… where x.age not in ?1</td>
</tr>
<tr>
<td>True</td>
<td>findByActiveTrue()</td>
<td>… where x.active = true</td>
</tr>
<tr>
<td>False</td>
<td>findByActiveFalse()</td>
<td>… where x.active = false</td>
</tr>
<tr>
<td>IgnoreCase</td>
<td>findByFirstnameIgnoreCase</td>
<td>… where UPPER(x.firstame) = UPPER(?1)</td>
</tr>
</tbody></table>
</li>
</ol>
<hr>
<h5 id="查询方法解析流程"><a href="#查询方法解析流程" class="headerlink" title="查询方法解析流程"></a>查询方法解析流程</h5><ul>
<li>假如创建一个查询：findByUserDepUuid()，则框架在解析该方法时，首先剔除 findBy，然后对剩下的属性进行解析，假设查询实体为 Doc<ul>
<li>先判断 userDepUuid（根据 POJO 规范，首字母变小写）是否为查询实体的一个属性，如果是，则表示根据该属性进行查询。如果没有该属性，则进行下一步</li>
<li>从右往左截取地一个大写字母开头的字符串（此处为 Uuid ），然后检查剩下的字符串是否为查询实体的一个属性，如果是，则表示根据该属性进行查询，如果没有该属性，则重复本步骤，继续从右往左截取。最后假设 user 为查询实体的一个属性</li>
<li>接着处理剩下部分（ DepUuid ），先判断 user 所对应的类型是否有 depUuid 属性，如果有，则表示该方法最终是根据 “Doc.user.depUuid” 的取值进行查询，否则继续按照上一步的规则从右往左截取，最终表示根据 “Doc.user.dep.uuid” 的值进行查询</li>
<li>可能会存在一种特殊情况，假设 Doc 包含一个 user 的属性，也有一个 userDep 属性，此时会存在混淆。可以明确在属性之间加上 “_” 以显式表达意图</li>
</ul>
</li>
<li>还可以直接在方法的参数上加入分页或者排序的参数<ul>
<li>Page&lt;User&gt; findByName(String name, Pageable pageable)</li>
<li>List&lt;User&gt; findByName(String name, Sort sort)</li>
</ul>
</li>
</ul>
<hr>
<h5 id="使用-Query-注解"><a href="#使用-Query-注解" class="headerlink" title="使用 @Query 注解"></a>使用 @Query 注解</h5><ol>
<li>可以声明在 Repository 方法中，摆脱像命名查询那样的约束，将查询直接在相应的接口方法中声明，结构更清晰</li>
<li>索引参数<ul>
<li>形如 <code>?X</code>，索引值从 1 开始，查询中 <code>?X</code> 个数需要与方法定义的参数个数相一致，切顺序也需要一致</li>
</ul>
</li>
<li>命名参数<ul>
<li>形如 <code>:named</code>，可以定义好参数名，赋值时采用 @Param(“参数名”)，顺序无需一致</li>
</ul>
</li>
<li>若 @Query 注解中有 LIKE 关键字，则后面的参数可以直接加 <code>%</code>，这样在传递参数值时就可以不加</li>
<li>也可以使用 @Query 注解来指定本地查询，需要设置 nativeQuery 属性为 true</li>
</ol>
<hr>
<h5 id="Modifying-注解和事务"><a href="#Modifying-注解和事务" class="headerlink" title="@Modifying 注解和事务"></a>@Modifying 注解和事务</h5><ol>
<li>@Query 与 @Modifying 两个注解一起声明，可以自定义更新操作，当只涉及某些字段更新时最常用</li>
<li>方法的返回值应该是 int，表示更新语句所影响的行数</li>
<li>在调用的地方必须添加事务，没有事务无法正常执行</li>
<li>Spring Data 提供了默认的事务处理方式，即所有的查询均声明为只读事务</li>
<li>对于自定义的方法，如需改变 Spring Data 提供的事务默认方式，可以在方法上添加 @Transactional 注解</li>
<li>进行多个 Repository 操作时，也应该使它们在同一个事务中处理，按照 MVC 的思想，这部分属于 Service 层，因此，需要在 Service 层实现对多个 Repository 的调用，并在相应方法上声明事务</li>
</ol>
<hr>
<h5 id="CrudRepository-接口"><a href="#CrudRepository-接口" class="headerlink" title="CrudRepository 接口"></a>CrudRepository 接口</h5><ol>
<li>CrudRepository 接口提供了最基本的对实体类的增删改查操作<ul>
<li>&lt;S extends T&gt; S save(S entity)：保存单个实体</li>
<li>&lt;S extends T&gt; Iterable&lt;S&gt; saveAll(Iterable&lt;S&gt; entities)：保存集合（批量保存）</li>
<li>Optional&lt;T&gt; findById(ID id)：根据 id 查找实体</li>
<li>boolean existsById(ID id)：根据 id 判断实体是否存在</li>
<li>Iterable&lt;T&gt; findAll()：查询所有的实体（不建议使用）</li>
<li>Iterable&lt;T&gt; findAllById(Iterable&lt;ID&gt; ids)：根据给定的 id 集合查询实体</li>
<li>long count()：查询实体数量</li>
<li>void deleteById(ID id)：根据 id 删除实体</li>
<li>void delete(T entity)：删除一个实体</li>
<li>void deleteAll(Iterable&lt;? extends T&gt; entities)：删除给定实体集合</li>
<li>void deleteAll()：删除所有实体（不建议使用）</li>
</ul>
</li>
</ol>
<hr>
<h5 id="PagingAndSortingRepository-接口"><a href="#PagingAndSortingRepository-接口" class="headerlink" title="PagingAndSortingRepository 接口"></a>PagingAndSortingRepository 接口</h5><ol>
<li>该接口在 CrudRepository 接口的基础上提供了分页与排序的功能<ul>
<li>Iterable&lt;T&gt; findAll(Sort sort)：排序</li>
<li>Page&lt;T&gt; findAll(Pageable pageable)：分页（包含排序）</li>
</ul>
</li>
<li>Pageable 接口通常使用其实现类 PageRequest，其中封装了分页需要的信息。Sort 类封装了排序的信息。Sort 类构造器中的 Order 指的是具体针对某一个属性进行升序排序还是降序排序</li>
</ol>
<hr>
<h5 id="JpaRepository-接口"><a href="#JpaRepository-接口" class="headerlink" title="JpaRepository 接口"></a>JpaRepository 接口</h5><ol>
<li>该接口在 PagingAndSortingRepository 接口的基础上提供了 JPA 的相关功能<ul>
<li>void flush()：刷新缓存</li>
<li>&lt;S extends T&gt; S saveAndFlush(S entity)：类似于 JPA 的 merge() 方法</li>
<li>void deleteInBatch(Iterable&lt;T&gt; entities)：删除一个实体集合</li>
</ul>
</li>
</ol>
<hr>
<h5 id="JpaSpecificationExecutor-接口"><a href="#JpaSpecificationExecutor-接口" class="headerlink" title="JpaSpecificationExecutor 接口"></a>JpaSpecificationExecutor 接口</h5><ol>
<li><p>实现一组 JPA Criteria 查询相关的方法</p>
<p> <img src="JpaSpecificationExecutor_Function.png" alt="JpaSpecificationExecutor_Function"></p>
</li>
<li><p>Specification：封装 JPA Criteria 的查询条件，通常使用匿名内部类的方式来创建该接口的对象</p>
<ul>
<li>Predicate toPredicate(Root&lt;T&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder criteriaBuilder)<ul>
<li>root：代表查询的实体类</li>
<li>query：可以从中得到 Root 对象，即告知 JPA Criteria 查询要查询哪一个实体类，也可以用来添加查询条件，还可以结合 EntityManager 对象得到最终查询的 TypedQuery 对象</li>
<li>criteriaBuilder：用于创建 Criteria 相关对象的工厂，可以从中获取到 Predicate 对象</li>
</ul>
</li>
</ul>
</li>
</ol>
<hr>
<h5 id="自定义-Repository-方法"><a href="#自定义-Repository-方法" class="headerlink" title="自定义 Repository 方法"></a>自定义 Repository 方法</h5><ol>
<li>为某一个 Repository 接口上添加自定义方法<ul>
<li>定义一个接口，声明自定义的方法</li>
<li>提供该自定义接口的实现类（并实现自定义接口中的方法），类名需要在自定义接口的名字的基础上加上 Impl</li>
<li>在 XxxRepository 接口上继承自定义的接口即可</li>
<li>注：默认情况下，Spring Data 会在 base-package 中查找 “自定义接口名Impl” 作为实现类，也可以通过 repository-impl-postfix 声明后缀</li>
</ul>
</li>
<li>为所有的 Repository 接口都添加自定义方法<ul>
<li>声明一个接口，在该接口中声明需要自定义的方法，且该接口需要继承 Spring Data 的 Repository 接口</li>
<li>提供上一步的接口的实现类，且继承 SimpleJpaRepository，并提供方法的实现</li>
<li>定义 JpaRepositoryFactoryBean 的实现类，使其生成第一步定义的接口实现类的对象</li>
<li>修改 &lt;jpa:repositories&gt; 节点的 factory-class 属性，使其指向自定义的 JpaRepositoryFactoryBean 的实现类的全类名</li>
<li>注意：全局的扩展实现类不要使用 Impl 作为后缀名。或者为全局扩展接口添加 @NoRepositoryBean 注解让 Spring Data 不认为它是一个 Repository</li>
</ul>
</li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JPA/" rel="tag"># JPA</a>
              <a href="/tags/Spring-Data/" rel="tag"># Spring Data</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
                <a href="/JPA/JPA/" rel="next" title="JPA">
                  <i class="fa fa-chevron-left"></i> JPA
                </a>
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
            </div>
          </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-5"><a class="nav-link" href="#Spring-Data-概述"><span class="nav-number">1.</span> <span class="nav-text">Spring Data 概述</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Spring-Data-JPA-概述"><span class="nav-number">2.</span> <span class="nav-text">Spring Data JPA 概述</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Spring-Data-JPA-开发步骤"><span class="nav-number">3.</span> <span class="nav-text">Spring Data JPA 开发步骤</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Repository-接口"><span class="nav-number">4.</span> <span class="nav-text">Repository 接口</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Spring-Data-JPA-方法定义规范"><span class="nav-number">5.</span> <span class="nav-text">Spring Data JPA 方法定义规范</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#查询方法解析流程"><span class="nav-number">6.</span> <span class="nav-text">查询方法解析流程</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#使用-Query-注解"><span class="nav-number">7.</span> <span class="nav-text">使用 @Query 注解</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Modifying-注解和事务"><span class="nav-number">8.</span> <span class="nav-text">@Modifying 注解和事务</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#CrudRepository-接口"><span class="nav-number">9.</span> <span class="nav-text">CrudRepository 接口</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#PagingAndSortingRepository-接口"><span class="nav-number">10.</span> <span class="nav-text">PagingAndSortingRepository 接口</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#JpaRepository-接口"><span class="nav-number">11.</span> <span class="nav-text">JpaRepository 接口</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#JpaSpecificationExecutor-接口"><span class="nav-number">12.</span> <span class="nav-text">JpaSpecificationExecutor 接口</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#自定义-Repository-方法"><span class="nav-number">13.</span> <span class="nav-text">自定义 Repository 方法</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="site-author-image" itemprop="image" alt="beiranc"
    src="/images/head.jpg">
  <p class="site-author-name" itemprop="name">beiranc</p>
  <div class="site-description" itemprop="description">你在想peach</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">11</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/beiranc" title="GitHub &amp;rarr; https:&#x2F;&#x2F;github.com&#x2F;beiranc" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a>
      </span>
      <span class="links-of-author-item">
        <a href="/mailto:beiranlp@gmail.com" title="E-Mail &amp;rarr; mailto:beiranlp@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a>
      </span>
      <span class="links-of-author-item">
        <a href="https://plus.google.com/lintsky" title="Google &amp;rarr; https:&#x2F;&#x2F;plus.google.com&#x2F;lintsky" rel="noopener" target="_blank"><i class="fa fa-fw fa-google"></i></a>
      </span>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">beiranc<br>Hosted By <a href="https://pages.github.com" target="_blank">GitHub Pages</a></span>
</div>

        












        
      </div>
    </footer>
  </div>

  
  
  <script color='0,0,255' opacity='0.5' zIndex='-1' count='99' src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1/canvas-nest.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script>



  
















  

  

</body>
</html>
